package com.ruoyi.project.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.WxOpenConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.wechat.controller.WxThirdPartyController;
import com.ruoyi.project.wechat.domain.ExtConfig;
import com.ruoyi.project.wechat.domain.ExtConfigExample;
import com.ruoyi.project.wechat.domain.WxOpenMaCodeTemplateCustom;
import com.ruoyi.project.wechat.domain.XcxVersion;
import com.ruoyi.project.wechat.service.ExtConfigService;
import com.ruoyi.project.wechat.service.WxOpenLoginConfigService;
import com.ruoyi.project.wechat.service.WxThirdPartyService;
import com.ruoyi.project.wechat.service.XcxVersionService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.api.WxOpenComponentService;
import me.chanjar.weixin.open.api.WxOpenMaService;
import me.chanjar.weixin.open.bean.ma.WxMaOpenCommitExtInfo;
import me.chanjar.weixin.open.bean.ma.WxMaOpenWindow;
import me.chanjar.weixin.open.bean.result.WxOpenResult;
import me.chanjar.weixin.open.util.json.WxOpenGsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WxThirdPartyServiceImpl implements WxThirdPartyService {

    private static final Logger logger = LoggerFactory.getLogger(WxThirdPartyServiceImpl.class);
    @Resource
    private WxOpenComponentService wxOpenComponentService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private XcxVersionService xcxVersionService;

    @Resource
    private ExtConfigService extConfigService;

    @Resource
    private WxOpenLoginConfigService wxOpenLoginConfigService;

    @Override
    public List<WxOpenMaCodeTemplateCustom> getTemplateDraftList() throws WxErrorException {
        String accessToken  = wxOpenComponentService.get(WxOpenConstants.GET_TEMPLATE_DRAFT_LIST_URL, "access_token");
        JsonParser jsonParser = new JsonParser();
        List<WxOpenMaCodeTemplateCustom> list = new ArrayList<>();
        JsonObject response = jsonParser.parse(StringUtils.defaultString(accessToken, "{}")).getAsJsonObject();
        boolean hasDraftList = response.has("draft_list");
        if (hasDraftList) {
            list = WxOpenGsonBuilder.create().fromJson(response.getAsJsonArray("draft_list"),
                    new TypeToken<List<WxOpenMaCodeTemplateCustom>>() {
                    }.getType());
        }
        return list;
    }

    @Override
    public List<WxOpenMaCodeTemplateCustom> getTemplateList() throws WxErrorException {
        String accessToken = wxOpenComponentService.get(WxOpenConstants.GET_TEMPLATE_LIST_URL, "access_token");
        JsonParser jsonParser = new JsonParser();
        List<WxOpenMaCodeTemplateCustom> list = new ArrayList<>();
        JsonObject response = jsonParser.parse(StringUtils.defaultString(accessToken, "{}")).getAsJsonObject();
        boolean hasDraftList = response.has("template_list");
        if (hasDraftList) {
            list = WxOpenGsonBuilder.create().fromJson(response.getAsJsonArray("template_list"),
                    new TypeToken<List<WxOpenMaCodeTemplateCustom>>() {
                    }.getType());
        }
        return list;
    }

    @Override
    public void addToTemplate(Long draftId) throws WxErrorException {
        wxOpenComponentService.addToTemplate(draftId);
    }

    @Override
    public void deleteTemplate(Long templateId) throws WxErrorException {
        wxOpenComponentService.deleteTemplate(templateId);
    }

    @Override
    public AjaxResult wxCommit(XcxVersion xcxVersion) throws WxErrorException {
        String appId = xcxVersion.getAppId();
        //判断是否已经授权登录
        String authorizerToken = wxOpenLoginConfigService.getAuthorizerToken(appId);
        if(StringUtils.isEmpty(authorizerToken)){
            //没有授权 或  失效--> 调用第三方扫码登录
            return AjaxResult.error(HttpStatus.UNAUTHORIZED,"未授权");
        }
        //未失效--> 提交代码
        //查询ext配置
        WxOpenMaService service = wxOpenComponentService.getWxMaServiceByAppid(appId);
        List<ExtConfig> configList = extConfigService.selectByExample(new ExtConfigExample());
        WxMaOpenCommitExtInfo extInfo = WxMaOpenCommitExtInfo.INSTANCE();
        if(configList.size() > 0){
            ExtConfig extConfig = configList.get(0);
            extInfo.setExtAppid(extConfig.getExtAppid());
            extInfo.setExtEnable(extConfig.getExtEnable());
            extInfo.setDirectCommit(extConfig.getDirectCommit());
            WxMaOpenWindow wxMaOpenWindow = new WxMaOpenWindow();
            wxMaOpenWindow.setNavigationBarTitleText(extConfig.getNavigationBarTitleText());
            JSONObject jsonObject = JSONObject.parseObject(extConfig.getExtMap());
            Map<String, Object> extMap = (Map<String, Object>) jsonObject;
            extInfo.setWindow(wxMaOpenWindow);
            extInfo.setExtMap(extMap);
            logger.info("上传代码提交的ext配置："+extInfo.toString());
        }else{
            return AjaxResult.error("ext没有配置");
        }
        WxOpenResult wxOpenResult = service.codeCommit(Long.parseLong(xcxVersion.getTemplateId()),xcxVersion.getUserVersion(),xcxVersion.getUserDesc(),extInfo);
        xcxVersion.setCreateTime(new Date());
        xcxVersion.setCreateBy(SecurityUtils.getUsername());
        xcxVersionService.insert(xcxVersion);
        return AjaxResult.success(wxOpenResult);
    }
}
